<template>
  <div class="login-container" :style="{backgroundImage:`url(${imgSrc})`}">
    <el-form ref="formRef" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">系统登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <el-icon><User /></el-icon>
        </span>
        <el-input
          class="el-input"
          v-model="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <el-icon><Lock /></el-icon>
        </span>
        <el-input
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          auto-complete="on"
          @keyup.enter="handleLogin"
        />
        <el-tooltip v-if="capsTooltip" content="Caps lock is On" placement="right">
          <el-icon><Warning /></el-icon>
        </el-tooltip>
        <span class="show-pwd" @click="showPwd">
          <el-icon><View v-if="passwordType === 'password'" /><Hide v-else /></el-icon>
        </span>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:90%;margin-bottom:30px;height: 40px;margin-left: 5%" @click="handleLogin">
        登录
      </el-button>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import JSEncrypt from 'jsencrypt'
import { Warning, User, Lock, View, Hide } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import loginBg from '@/assets/backgd-image/backimg.jpg'

// 获取router和route实例
const router = useRouter()
const route = useRoute()

// 表单引用
const loginForm = reactive({
  username: '',
  password: ''
})

// 定义表单验证规则
const validatePassword = (rule: any, value: string, callback: any) => {
  if (value.length < 6) {
    callback(new Error('The password can not be less than 6 digits'))
  } else {
    callback()
  }
}

const loginRules = reactive<FormRules>({
  username: [{ required: true, trigger: 'blur' }],
  password: [{ required: true, trigger: 'blur', validator: validatePassword }]
})

// 其他响应式数据
const imgSrc = ref(loginBg)
const passwordType = ref('password')
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvmPZ6CZYjw4DdQSWP0Ah
0Z4XbKzJeV2DkYUrFOe58clOHsv0JbPVS1aFRh1zZU0v1ULJ7zL3ztCN9oFbCvYm
IuDjTs6IIbUANLhg3Vo3SQwPcDj8a9hzrxkstpzadta6lpaN4rBtaNJBdwxizIfR
PCKhdYaQZbGBgtrCWmMMxv4r7Ma5iHeAwMOzk6cDpKRSERxNktBg8poFpstum2ZC
f/FastnMtRhT4aTPMqabuUwVmZ53rkaso0lcpjm0m0TGMRaJxFGHinxqb0/fWCze
pfRAWjF7B01QxfGyOQI81vXJRP0LSXcNez2FOzT9Nk7732rLImplHgVGA5L3Oc/q
bwIDAQAB
-----END PUBLIC KEY-----`
const capsTooltip = ref(false)
const loading = ref(false)
const formRef = ref<InstanceType<typeof FormInstance>>()
// const usernameRef = ref<any>(null)
// const passwordRef = ref<any>(null)

// 重定向相关
const redirect = ref<string | undefined>(undefined)
const otherQuery = ref({})

// 获取其他查询参数
const getOtherQuery = (query: any) => {
  return Object.keys(query).reduce((acc: any, cur) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur]
    }
    return acc
  }, {})
}

// 路由变更处理
watch(() => route.query, (query) => {
  if (query) {
    redirect.value = query.redirect as string
    otherQuery.value = getOtherQuery(query)
  }
}, { immediate: true })

// 处理登录
const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const userStore = useUserStore()
        const { username, password } = loginForm

        // 密码RSA加密处理
        const encryptor = new JSEncrypt()
        encryptor.setPublicKey(publicKey)
        const encryptedPassword = encryptor.encrypt(password)
        if (!encryptedPassword) {
          throw new Error('密码加密失败')
        }

        const loginData = {
          username: username.trim(),
          password: encryptedPassword
        }
        console.log('Login Request Data:', loginData)

        // 登录
        await userStore.login(loginData)
        // 获取用户信息
        await userStore.getInfo()

        ElMessage.success('登录成功')
        router.push({ path: redirect.value || '/', query: otherQuery.value })
      } catch (error: any) {
        console.error('Login Error:', {
          message: error.message,
          response: error.response,
          config: error.config
        })
        ElMessage.error(error.response?.data?.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}

// 显示/隐藏密码
const showPwd = () => {
  passwordType.value = passwordType.value === 'password' ? '' : 'password'
}

// 处理大小写锁定
const checkCapslock = (e: KeyboardEvent) => {
  const { key } = e
  capsTooltip.value = key && key.length === 1 && (key >= 'A' && key <= 'Z') && !(e.shiftKey && e.getModifierState('CapsLock'))
}

onMounted(() => {
  window.addEventListener('keydown', checkCapslock)
  // 清除旧的 token
  const userStore = useUserStore()
  userStore.logout()
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', checkCapslock)
})
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#5c646d;
$light_gray:#fff;
$color-black: #000;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: calc(100% - 50px);

    input {
      background: transparent;
      border: 0;
      -webkit-appearance: none;
      border-radius: 0;
      padding: 12px 5px 12px 15px;
      font-size: 15px;
      color: $color-black;
      height: 47px;
      caret-color: $color-black;
      width: 100%;

      &:-webkit-autofill {
        box-shadow: 0 0 0 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-input__wrapper{
    width: 100% !important;
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: $bg;
    border-radius: 5px;
    color: #454545;
    margin-left: 20px;
    margin-right: 20px;
    display: flex;
    align-items: center;
  }

  .login-btn{
    width: calc(100% - 40px);
    height: 45px!important;
    margin-left: 20px;
    margin-right: 20px;
    margin-bottom: 30px;
    border: 0;
    font-size: 16px;
    font-weight: bold;
    // opacity: 0.9;
    border-radius: 20px;
    background-image: linear-gradient(to right, #74ebd5 0%, #9face6 100%);
  }

  .login-btn:hover{
    color: greenyellow;
    background-image: linear-gradient(to right, #eea2a2 0%, #bbc1bf 19%, #57c6e1 42%, #b49fda 79%, #7ac5d8 100%);
  }
}
</style>

<style lang="scss" scoped>
$bg:#5c646d;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  height: 100%;
  background-color: $bg;
  // overflow: hidden;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-form {
    // position: relative;
    width: 520px;
    max-width: 100%;
    // padding: 160px 35px 0;
    // margin: 0 auto;
    background-color: rgba(0,0,0,0.5);
    // overflow: hidden;
    border-radius: 8px;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    flex-shrink: 0;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 20px auto 20px auto;
      text-align: center;
      font-weight: bold;
      // letter-spacing: 2px;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
